#include "receivingformdialog.h"
#include "ui_receivingformdialog.h"

#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlError>
#include <QMessageBox>
ReceivingFormDialog::ReceivingFormDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ReceivingFormDialog)
{
    ui->setupUi(this);

    //初始化数据
    initData();

    //连接信号
    connect(ui->cmbOrder, &QComboBox::currentTextChanged, this, &ReceivingFormDialog::onOrderSelected);
}

ReceivingFormDialog::~ReceivingFormDialog()
{
    delete ui;
}

void ReceivingFormDialog::on_buttonBox_accepted()
{

    //提交表单
    onSubmit();
    //发送关闭信号
    emit reportDialogClosed();
    //关闭对话框并返回
    accept();
}


void ReceivingFormDialog::on_buttonBox_rejected()
{
    //发送关闭信号
    emit reportDialogClosed();
    //关闭对话框并返回
    reject();
}

void ReceivingFormDialog::onOrderSelected(const QString &orderId)
{
    if (orderId == "--请选择采购订单编号--")
    {
        clearOrderInfo();
        return;
    }
    //加载基本信息
    QSqlQuery infoQuery;
    infoQuery.prepare(
        "SELECT po.order_date, s.name, po.delivery_terms "
        "FROM PurchaseOrder po "
        "JOIN Supplier s ON po.supplier_id = s.supplier_id "
        "WHERE po.po_id = ?"
    );
    infoQuery.addBindValue(orderId);
    if (infoQuery.exec() && infoQuery.next()) {
        ui->lblOrderDate->setText(QString("下单日期：%1").arg(infoQuery.value("order_date").toString()));
        ui->lblSupplier->setText(QString("供应商：%1").arg(infoQuery.value("name").toString()));
        ui->lblDeliveryTerms->setText(QString("付款条件：%1").arg(infoQuery.value("delivery_terms").toString()));
    }

    //加载订单明细
    QSqlQueryModel *model = new QSqlQueryModel(this);
    model->setQuery(
                    "SELECT p.name AS '产品名称', p.spec AS '规格', pod.quantity AS '数量', "
                    "pod.unit_price AS '单价', (pod.quantity * pod.unit_price) AS '金额' "
                    "FROM PurchaseOrderDetail pod "
                    "JOIN SupplierProduct sp ON pod.supplier_product_id = sp.supplier_product_id "
                    "JOIN Product p ON sp.product_id = p.product_id "
                    "WHERE pod.po_id = " + orderId
    );
    ui->tableView->setModel(model);

    //计算总金额
    double total = 0.00;
    for (int row = 0; row < model->rowCount(); row++)
    {
        total += model->data(model->index(row, 4)).toDouble();
    }
    ui->lblTotalAmount->setText(QString("总金额：%1").arg(total, 0, 'f', 2));
}

void ReceivingFormDialog::closeEvent(QCloseEvent *event)
{
    //发送关闭信号
    emit reportDialogClosed();
    event->accept();
}

void ReceivingFormDialog::initData()
{
    //初始化采购订单编号下拉框
    QSqlQuery query("SELECT po_id FROM PurchaseOrder WHERE order_status = '已送达'");
    ui->cmbOrder->addItem("--请选择采购订单编号--");
    while (query.next())
    {
        ui->cmbOrder->addItem(query.value(0).toString());
    }
    //初始化检查结果下拉框
    ui->cmbResult->addItems({"合格", "不合格"});
}

void ReceivingFormDialog::onSubmit()
{
    //获取表单数据
    QString reportId = ui->leReportId->text();
    QString inspector = ui->leInspector->text();
    QString orderId = ui->cmbOrder->currentText();
    QString result = ui->cmbResult->currentText();
    QString reason = ui->leRejection->text();

    // 验证数据
    if (reportId.isEmpty() || inspector.isEmpty() || orderId.isEmpty())
    {
        QMessageBox::warning(this, "错误", "请填写必填字段");
        return;
    }

    if (result == "不合格" && reason.isEmpty())
    {
        QMessageBox::warning(this, "错误", "验收不合格时必须填写拒收原因");
        return;
    }
    // 准备调用存储过程
    QSqlQuery query;
    query.prepare("CALL CreateReceivingReport(?, ?, ?, ?, ?, @out_result)");
    query.addBindValue(reportId.toInt());
    query.addBindValue(orderId.toInt());
    query.addBindValue(inspector);
    query.addBindValue(result);
    query.addBindValue(result == "合格" ? QVariant() : reason);

    if (!query.exec())
    {
        QMessageBox::critical(this, "错误", "执行存储过程失败: " + query.lastError().text());
        return;
    }

    // 获取存储过程输出结果
    query.exec("SELECT @out_result");
    if (query.next())
    {
        int resultCode = query.value(0).toInt();

        if (resultCode == 1)
        {
            QMessageBox::information(this, "成功", "验收单创建成功");
        } else
        {
            QMessageBox::warning(this, "失败", "验收单创建失败");
        }
    } else
    {
        QMessageBox::critical(this, "错误", "无法获取存储过程结果");
    }
}

void ReceivingFormDialog::clearOrderInfo()
{
    // 清除基本信息
    ui->lblOrderDate->setText("下单日期：");
    ui->lblSupplier->setText("供应商：");
    ui->lblDeliveryTerms->setText("付款条件：");

    // 清除表格数据
    QSqlQueryModel *emptyModel = new QSqlQueryModel(this);
    ui->tableView->setModel(emptyModel);

    // 清除总金额
    ui->lblTotalAmount->setText("总金额：0.00");
}

